package response

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"gitee.com/git-lz/twelve/common/merrors"
	"gitee.com/git-lz/twelve/common/xtrace"
)

type Response struct {
	Errno   int         `json:"code"`
	Msg     string      `json:"message"`
	Data    interface{} `json:"data"`
	IsSucc  bool        `json:"is_succ"`
	TraceId string      `json:"trace_id"`
	Page    *PageInfo   `json:"page,omitempty"`
}

type PageInfo struct {
	PageNumber int   `json:"pageNumber"`
	PageSize   int   `json:"pageSize"`
	TotalPage  int   `json:"totalPage"`
	TotalSize  int64 `json:"totalSize"`
}

func NewResponse() *Response {
	return &Response{
		IsSucc: true,
	}
}

func (r *Response) WithDefaultMsg(errno int) *Response {
	tx := r
	msg, ok := merrors.ErrnoMsgMap[errno]
	if !ok {
		msg = "unknown error"
	}

	if errno != merrors.ErrnoSuccess {
		tx.IsSucc = false
	}

	tx.Msg = msg
	tx.Errno = errno
	return tx
}

func (r *Response) WithMsg(errno int, msg string) *Response {
	tx := r
	if errno != merrors.ErrnoSuccess {
		tx.IsSucc = false
	}

	tx.Msg = msg
	tx.Errno = errno
	return tx
}

func (r *Response) WithData(data interface{}) *Response {
	tx := r

	if tx.Errno != merrors.ErrnoSuccess {
		tx.IsSucc = false
	}

	tx.Data = data
	return tx
}

func (r *Response) WithPage(page *PageInfo) *Response {
	tx := r

	if tx.Errno != merrors.ErrnoSuccess {
		tx.IsSucc = false
	}

	tx.Page = page
	return tx
}

func EchoResponse(ctx *gin.Context, resp *Response) {
	resp.TraceId = xtrace.TraceIdFromContext(ctx)
	if resp.Errno != merrors.ErrnoSuccess {
		resp.IsSucc = false
	} else {
		resp.IsSucc = true
	}

	ctx.JSON(http.StatusOK, resp)
}
